<template>
  <el-dialog ref="MessageDialog" :visible.sync="dialogVisible" title="私信" width="60%">
    <message-form ref="MessageForm" :receiver="authorName" :sender="sender" @submit="createMessage"/>
    <message-list :messages="messages" @delete="deleteMessage"/>
  </el-dialog>
</template>

<script>
import MessageForm from "./MessageForm.vue";
import MessageList from "./MessageList.vue";
import axios from "axios";

export default {
  name: "MessageDialog",
  components: {
    MessageForm,
    MessageList,
  },
  props: {
    sender: String,
    authorName: String,
  },
  data() {
    return {
      dialogVisible: false,
      messages: [],
    };
  },
  methods: {
    createMessage(message) {
      axios
          .post(`/api/messages` , message)
          .then((response) => {
            this.messages.unshift(response.data);
            // this.$refs.messageForm.submitForm(response.data)
          })
          .catch((error) => {
            console.log(error);
          });
    },
    getCurrentUser() {
      return this.$store.state.user.username;
    },

    getAuthorName() {
      return this.user.username;
    },
    deleteMessage(id) {
      axios
          .delete("/api/messages/" + id)
          .then(() => {
            this.messages = this.messages.filter((message) =>
                message.id !== id);
          })
          .catch((error) => {
            console.log(error);
          });
    },
    show() {
      axios
          .get(`/api/messages/${this.$store.getters.user.username}/${this.authorName}`)
          .then((response) => {
            console.log(this.$store);
            this.messages = response.data;
            this.dialogVisible = true;
            console.log(this.messages);
          })
          .catch((error) => {
            console.log(error);
          });
    },
    hide() {
      this.dialogVisible = false;
      this.clearForm();
    },
    clearForm() {
      this.$nextTick(() => {
        this.$refs.MessageForm.clearForm();
      });
    },
  },
};
</script>